package com.mianyang.zhangsan.plugin.export.parse;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author jiangjr
 * @date 2022-09-30
 */
@Slf4j
public class HtmlParse {
    private String template;
    private final String table = "table";

    public HtmlParse(String template){
        this.template = template;
    }

    public  <T> String combination(String key, T data) {
        if (data == null) {
            return this.template;
        }
        if (key.startsWith(table)){
            if (data instanceof List){
                StringBuilder tbody = new StringBuilder();
                for (Object datum : (List) data) {
                    StringBuilder tr = new StringBuilder();
                    tr.append("<tr>");
                    Field[] fields = datum.getClass().getDeclaredFields();
                    for (Field field : fields){
                        String var1 = "";
                        try {
                            field.setAccessible(true);
                            var1 = field.get(datum).toString();
                        } catch (IllegalAccessException e) {
                            log.error("pdf生成异常");
                        }
                        tr.append("<td>").append(var1).append("</td>");
                    }
                    tr.append("</tr>");
                    tbody.append(tr);
                }
                matchAndReplace(key, tbody.toString());
            }
        }else {
            matchAndReplace(key, data.toString());
        }
        return this.template;
    }

    private void matchAndReplace(String key, String value){
        StringBuffer sb = new StringBuffer();
        Matcher matcher = Pattern.compile("\\$\\{" + key + "\\}").matcher(template);
        if (matcher.find()){
            matcher.appendReplacement(sb, value);
            matcher.appendTail(sb);
        }
        this.template = sb.toString();
    }
}
